#！/usr/bin/python
# _*_ coding:UTF-8 -*-
from datetime import date, datetime
import os
import datetime
import pandas as pd
from tqdm import tqdm
import func
import config as config
def getCode(n):
    '''
    根据参数n判断是否读取
    '''
    #读取 股票代码文件
    # cpath = os.getcwd().replace('\\','/')
    tdx_stocks = pd.read_csv(  config.tdx['info_code_path'],
        dtype={0:str},header=None,index_col=None,encoding='gbk',sep="|")
    for item in tqdm(tdx_stocks[0]):
        # 6开头的是SH，否则就是SZ
        file_path = config.tdx['stock_path']+item+'.txt'
        # print(file_path)  #test
        dealFile(file_path)
    # dealFile(1) #test
    print('文件初始化完成')
def dealFile(file_path):
    # file_path = config.tdx['stock_path']+'/001213.txt'  #test
    columns= ['dates','begin','high','low','close','vol','money']
    # df = pd.read_csv(file_path,encoding='gbk',names=columns,header=1)
    # df2 = df[0:-1]
    # df2['dates'] = pd.to_datetime(df2['dates'])
    # df2.sort_values(by='dates',ascending=False,inplace=True)
    # print(df2)
    # print(df2.dtypes)
    try:
        df = pd.read_csv(file_path,encoding='gbk',names=columns,header=1,index_col='dates')[0:-1]
        # df.sort_index(ascending=False,inplace=True)  #此处inplace=True，实现就地排序，否则需要使用变量获取排序后的值
        # df = df.sort_index(ascending=False)
        #计算各均线
        ma_list=[5,10,20,30,60,90,120]
        for ma in ma_list:
            df=func.MA(df,ma)
        #计算涨幅
        df = func.rate(df)
        # 添加新列,量比，换手率，
        df['liang']=''
        df['hands']=''
        # 写入最后日期文件
        file_name = file_path[-10:-4]
        # print(file_name)
        # last_date = df.tail(1).index[0]
        # with open(os.getcwd()+config.save['last_path'], 'w+') as file:
        #     file.write(last_date+'\n')
        # 写入csv文件,此处一次性写入
        df.to_csv(os.getcwd()+'/data/csv/stock/'+file_name+'.csv', float_format='%.2f')
    except:
        print(file_path +' 数据不足')
    
        
   